package org.bees.cms.web.action;

import net.sf.json.JSONObject;

import org.bees.cms.common.Order;
import org.bees.cms.common.Page;
import org.bees.cms.core.Domain;
import org.bees.cms.core.clause.Adapter;
import org.bees.cms.core.clause.Criterion;
import org.bees.cms.web.util.JPAAdapter;
import org.bees.cms.web.util.Pages;

public abstract class PagingActionSupport<D extends Domain> extends ActionSupport<D> implements ServiceAction<D> {
	protected static Adapter adapter = new JPAAdapter();

	protected long current = 1;
	protected long capacity = 10;
	protected String condition;
	protected Order order;
	protected String by;

	@Override
	protected String doExecute() throws Exception {
		String _condition = condition == null ? null : condition.trim();
		if (_condition != null && _condition.startsWith("{") && _condition.endsWith("}")) {
			Criterion criterion = new Criterion();
			criterion.from(JSONObject.fromObject(_condition));
			_condition = criterion.toSQL(adapter, parameter, "o");
		}
		Page<D> page = query(current, capacity, _condition, order, by);
		request.setAttribute(Pages.PAGE, page);
		return SUCCESS;
	}

	protected Page<D> query(long current, long capacity, String condition, Order order, String by) throws Exception {
		return service().screen(current, capacity, condition, order, by);
	}

	public long getCurrent() {
		return current;
	}

	public void setCurrent(long current) {
		this.current = current;
	}

	public long getCapacity() {
		return capacity;
	}

	public void setCapacity(long capacity) {
		this.capacity = capacity;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public String getBy() {
		return by;
	}

	public void setBy(String by) {
		this.by = by;
	}

}
